package com.webserver.controllers;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.Article;


import java.io.*;

public class ArticleController {
    private static String articlesDir ="./articles/";
    static{
        File articleDir =new File(articlesDir);
        if (!articleDir.exists()){
            articleDir.mkdirs();
        }
    }

    public void writeArticle(HttpRequest request, HttpResponse response){
        System.out.println("处理发表文章操作！！！！！！！！！！");
        String title =request.getParameter("title");
        String author =request.getParameter("author");
        String content =request.getParameter("content");
        if(title==null || author==null || content==null) {
            File fail = new File("./webapps/myweb/article_fail.html");
            response.setEntity(fail);
            return;
        }
        File articleFile =new File(articlesDir + title + ".obj");
        if (articleFile.exists()){
            File fail =new File("./webapps/myweb/article_fail.html");
            response.setEntity(fail);
            return;
        }try (
                FileOutputStream fos = new FileOutputStream(articleFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ) {
            Article article = new Article(title,author,content);
            oos.writeObject(article);
            //3设置注册成功页面
            File success = new File("./webapps/myweb/article_success.html");
            response.setEntity(success);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
